package com.github.icloudpay.pay.core.service.schedule;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.github.icloudpay.pay.core.biz.PayOrderBiz;
import com.github.icloudpay.pay.core.biz.PaySerialBiz;
import com.github.icloudpay.pay.core.entity.PayChannelInterface;
import com.github.icloudpay.pay.core.entity.PayOrder;
import com.github.icloudpay.pay.core.entity.PaySerial;
import com.github.icloudpay.pay.core.inter.QueryPayStatusService;
import com.github.icloudpay.pay.core.inter.schedule.PaymdStatusService;
import com.github.icloudpay.pay.core.mapper.PayChannelInterfaceMapper;
import com.github.icloudpay.pay.core.service.pay.PayCallbackService;
import com.github.icloudpay.pay.core.util.DateUtil;
import com.github.icloudpay.pay.core.util.SpringContextHolder;
import com.github.wxiaoqi.security.common.admin.pay.request.CallbackRequest;
import com.github.wxiaoqi.security.common.admin.pay.request.QueryPayStatusRequest;
import com.github.wxiaoqi.security.common.admin.pay.response.QueryPayStatusResponse;

/**
 * 支付状态查询调度
 * @author hexufeng
 *
 */
@Service("paymdStatusService")
public class PaymdStatusServiceImpl implements PaymdStatusService{

	private static final Logger logger = LoggerFactory.getLogger(PaymdStatusServiceImpl.class);
	
	@Autowired
	private PaySerialBiz paySerialBiz;
	@Autowired
	private PayOrderBiz payOrderBiz;
	@Autowired
	private PayChannelInterfaceMapper payChannelInterfaceMapper;
	@Autowired
	private PayCallbackService payCallbackService;

	@Override
	public void PaymdStatus() {

		String endDateTime = DateUtil.getStandardDateTime();

		logger.info("定时查询支付流水状态,时间为：{}",endDateTime);

		int paySerialCount = paySerialBiz.getCountByDateTime(endDateTime);
		if(paySerialCount == 0){
			logger.info("时间为：{}之前,定时查询支付流水状态,支付流水表中不存在支付处理中的流水", endDateTime);
			return;
		}
		logger.info("需要去第三方支付公司查询的支付流水数量为：{}",paySerialCount);

		int count = paySerialCount%500==0?(paySerialCount/500):((paySerialCount/500)+1);
		for(int i = 0; i < count; i++){
			List<PaySerial> paySerialList = paySerialBiz.queryPaySerialList(endDateTime, 1, 500);
			if(paySerialList == null || paySerialList.size() == 0){
				logger.info("时间为：{}之前,定时查询支付状态,支付订单表中不存在支付处理中的订单", endDateTime);
				return;
			}
			for(int j = 0; j < paySerialList.size(); j++){
				ordStatusHandle(paySerialList.get(j));
			}
		}
	}
	
	/**
	 * 向第三方查询支付结果并更新状态
	 * @param paySerial
	 */
	@Transactional(propagation = Propagation.REQUIRES_NEW)
	private void ordStatusHandle(PaySerial paySerial){
		PayOrder payOrder = new PayOrder();
		payOrder.setPlatformId(paySerial.getPlatformId());
		payOrder.setPayOrderNo(paySerial.getPayOrderNo());
		PayOrder selectPayOrder = payOrderBiz.selectOne(payOrder);
		if(null == selectPayOrder){
			logger.info("订单号为：{}的订单不存在", paySerial.getPayOrderNo());
			return;
		}
		
		//根据支付通道查询查询请求方法
		PayChannelInterface payChannelInterface = new PayChannelInterface();
		payChannelInterface.setPayChannelNo(paySerial.getPayChannelNo());
		payChannelInterface.setTradeType("01");//支付查询
		PayChannelInterface selectInterface = payChannelInterfaceMapper.selectOne(payChannelInterface);
		if(null == selectInterface || null == selectInterface.getServiceName()){
			logger.info("支付通道为：{}的信息未配置", paySerial.getPayChannelNo());
			return;
		}
		
		QueryPayStatusService queryPayStatusService =  SpringContextHolder.getBean(selectInterface.getServiceName());
		QueryPayStatusRequest queryPayStatusRequest = new QueryPayStatusRequest();
		queryPayStatusRequest.setMerId(selectPayOrder.getMerchantId());
		queryPayStatusRequest.setOrderId(paySerial.getPayOrderNo());
		queryPayStatusRequest.setPayChannelNo(paySerial.getPayChannelNo());
		queryPayStatusRequest.setPayCompanyNo(paySerial.getPayCompanyNo());
		queryPayStatusRequest.setPlatformId(selectPayOrder.getPlatformId());
		QueryPayStatusResponse queryPayStatusResponse = queryPayStatusService.queryPayStatus(queryPayStatusRequest);
		if(!queryPayStatusResponse.isSuccess()){
			logger.info("向第三方查询支付结果失败,订单号.....{}", selectPayOrder.getPayOrderNo());
			return;
		}
		
		CallbackRequest callbackRequest = new CallbackRequest();
        callbackRequest.setRequestNo(paySerial.getSerialNo());
        callbackRequest.setOrderAmt(queryPayStatusResponse.getOrderAmt());
        callbackRequest.setRemoteTxJournalNo(queryPayStatusResponse.getRemoteTxJournalNo());
        callbackRequest.setPayChannelNo(paySerial.getPayChannelNo());
		if (queryPayStatusResponse.isPayStatus()) {
			logger.info("支付订单号为{}的支付交易状态为成功", selectPayOrder.getPayOrderNo());
			callbackRequest.setStatus("00");//成功
		}else if ("USERPAYING".equals(queryPayStatusResponse.getPayStatusStr())) {
            logger.info("支付订单号为{}的支付交易状态为支付处理中", selectPayOrder.getPayOrderNo());
        }else {
            logger.info("支付订单号为{}的支付交易状态为失败", selectPayOrder.getPayOrderNo());
            callbackRequest.setStatus("01");//失败
        }
		payCallbackService.callBack(callbackRequest);
	}

}
